package com.h3c.gm.schedule.task

import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.h3c.gm.common.constant.ScheduleURI
import com.h3c.gm.common.utils.SpringContextUtil
import com.h3c.gm.common.utils.UUIDUtils
import com.h3c.gm.entity.DO.BusUserDO
import com.h3c.gm.common.constant.HostOrgkeyPair
import com.h3c.gm.common.utils.HttpUtils
import com.h3c.gm.service.BusUserService

/**
 * Created by d14287 on 2017/7/7.
 */
class UserTask implements Runnable {
    HostOrgkeyPair hostOrgkeyPair
    BusUserService busUserService = SpringContextUtil.getBean(BusUserService.class)

    @Override
    void run() {
        Optional<JSONArray> optional = HttpUtils.httpGet(hostOrgkeyPair.getProc() + '://' + hostOrgkeyPair.getHost() + ScheduleURI.user_api_uri.replace('{host}', hostOrgkeyPair.getHost()))
        if (!optional.isPresent()) {
            return
        }
        JSONArray arrays = optional.get()
        //删除所有
        busUserService.deleteByOrgkey(hostOrgkeyPair.name())
        for (int i = 0; i < arrays.size(); i++) {
            JSONObject object = arrays.getJSONObject(i)
            BusUserDO userDO = new BusUserDO()
            userDO.setUserid(UUIDUtils.generateUUID())
            userDO.setRegtime(object.getDate('regtime'))
            userDO.setStatus(String.valueOf(object.getShort('status')))
            userDO.setAccount(object.getString('loginid'))
            userDO.setName(object.getString('username'))
            userDO.setOrgkey(hostOrgkeyPair.name())
            busUserService.insert(userDO)
        }
    }


    UserTask(HostOrgkeyPair hostOrgkeyPair) {
        this.hostOrgkeyPair = hostOrgkeyPair
    }
}
